<template>
  <view class="mall">
    <view
      class="px-base py-s search"
      style="padding-bottom: 4px"
      @click="onSearch"
    >
      <search />
    </view>
    <view class="flex flex-1 mall-content">
      <view class="mall-categories">
        <scroll-view scroll-y="true">
          <!-- 选项卡类别列表 -->
          <view
            class="leading-label"
            v-for="(item, index) in categories"
            :class="{ selected: isActive === index }"
            :key="item.id"
            :title="item.name || '-'"
            @click.stop="tabChoose(item, index)"
          >
            {{ item.name }}
          </view>
        </scroll-view>
      </view>

      <swiper
        @change="swiperChange"
        :current="isActive"
        class="swiper-content"
        :style="{ height: fullHeight + 'px' }"
        :vertical="true"
      >
        <swiper-item
          class="swiperitem-content"
          v-for="(item2, index) in categories"
          :key="item2.id"
        >
          <scroll-view
            v-if="isActive === index"
            scroll-y="true"
            class="swiper-content"
            @scroll="scrollChange"
            :style="{ height: fullHeight + 'px' }"
          >
            <view
              class="pt-20px pb-20px"
              v-if="categories[isActive - 1] && isScrollUp"
            >
              <view class="upScroll"
                ><image
                  :src="ossImg('others/goods/up.png')"
                  alt=""
                />下划继续浏览 {{ categories[isActive - 1].name }}</view
              >
            </view>

            <view class="flex-1 categories-content">
              <div class="py-18px categories-label">
                {{ item2.name }}
              </div>

              <view class="goods-list">
                <div
                  class="categories-cover cover"
                  :style="{ backgroundImage: `url(${item2.imageUrl})` }"
                ></div>
                <template v-if="classification.children[0]">
                  <view
                    v-for="child in item2.children"
                    class="child-category"
                    :key="child.id"
                    @click.stop="classification = child"
                  >
                    <view
                      class="categories-cover cover mb-5px"
                      :style="{ backgroundImage: `url(${child.imageUrl})` }"
                    ></view>
                    <view>{{ child.name }}</view>
                  </view>
                </template>

                <template v-else>
                  <view
                    class="mt-xl"
                    v-for="(item2, index) in goodsRecords"
                    :key="index"
                  >
                    <!-- <goods :info="item2" @add="openSkuChoose" /> -->
                    <view class="goods" @click.stop="toGoodsDetail(item2)">
                      <image class="cover" :src="item2.imageUrl" />
                      <view>
                        <view class="goods-title">
                          {{ item2.name }}
                        </view>
                        <view class="goods-price">
                          <view class="price">{{ item2.lowestPrice }}</view>
                          <view class="cart" @click.stop="openSkuChoose(item2)">
                            <image
                              src="https://scrm2-prod.oss-accelerate.aliyuncs.com/assets/others/component/cart.png"
                            />
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </template>

                <!--     填充自定义Tab-bar高度     -->
                <tab-bar-divider />
              </view>
            </view>
            <view class="pt-20px pb-20px">
              <view class="upScroll" v-if="categories[isActive + 1]">
                <image :src="ossImg('others/goods/down.png')" alt="" />
                上划继续浏览 {{ categories[isActive + 1].name }}
              </view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
    <back-home :cartCount="cartCount" right="40rpx">
      <jump-redirect-url>
        <image
          class="w-44px h-44px mb-4px block"
          :src="ossImg('others/OreoSnacksXEggyParty/jump_back_circle.png')"
        />
      </jump-redirect-url>
    </back-home>
  </view>
  <custom-tab-bar :current="3" :cartCount="cartCount" />
  <oreo-popup round :show="visible" position="bottom">
    <product-sku
      v-if="visible"
      :chooseType="'cart'"
      :product="currentProduct"
      @confirm="onAdd2Cart"
      @skuChange="handleSku"
      @close="visible = false"
    />
  </oreo-popup>


</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import Search from "@/components/search";
import Goods from "@/components/goods";
import BackHome from "@/components/back-home";
import TabBarDivider from "@/components/tab-bar-divider";
// import privacyPopup from "@/components/privacy-popup";

import {
  GetCategoryGoods,
  GetProductCategories,
  AddProduct2Cart,
} from "@/services/mall";
import ProductSku from "@/components/product-sku";
import { message, setCurrentTabBar, ossImg } from "@/utils/utils";
import { onShow, onUnload, onHide } from "@dcloudio/uni-app";
import CustomTabBar from "@/components/custom-tab-bar";
import JumpRedirectUrl from "@/components/jump-redirect-url.vue";

let enterTime = "";
let outTime = "";
let stayTime = "";

const classification = ref({ children: [] });
const categories = ref([]);
const goodsRecords = ref([]);
const visible = ref(false);
const currentProduct = ref({});
const cartCount = ref(getApp().globalData.cartCount);
const sku = ref("");
const fullHeight = ref(0);
const isActive = ref(0);
const isScrollUp = ref(false);
const isScrollDown = ref(false);

onMounted(() => {
  getCategories();
});
onShow(() => {
  console.log(ossImg("others/component/cart.png"));
  uni.getSystemInfo({
    success: (result) => {
      console.log(result);
      let info = uni.createSelectorQuery().select(".search");
      info
        .boundingClientRect(function (data) {
          //data - 各种参数
          console.log(11111, data); // 获取元素宽度
          const { windowHeight } = result;
          fullHeight.value = windowHeight - data.height - 50;
        })
        .exec();
    },
  });

  // 用户进入时间
  enterTime = new Date();
  setCurrentTabBar(2, false);
  if (uni.getStorageSync("TOKEN")) {
    getApp()
      .getCartCount()
      .then((res) => {
        cartCount.value = res;
      });
  }

  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    "all_products_page",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    "all_products_page",
    stayTime
  );
});

watch(
  () => classification.value,
  () => getGoods()
);

const getCategories = async () => {
  const { data } = await GetProductCategories({ productType: 1 });
  if (!data.length) return;
  classification.value = data[0];
  categories.value = data;
};

const getGoods = async () => {
  const { data } = await GetCategoryGoods({
    productType: 1,
    classificationId: classification.value.id,
  });
  goodsRecords.value = data;

  // 循环上报商品卡曝光  SDK 有队列缓存机制，会批量缓存后一起上报，不会影响性能。
  let skuList = [];
  for (const item of data) {
    skuList = [...skuList, ...item.productSkus];
  }
  for (const item of skuList) {
    getApp()
      .sr()
      .track("expose_sku_component", {
        sku: {
          sku_id: item.id, // 若商品无sku_id时，可传spu_id信息
          sku_name: skuLabel(item.spData), // 若商品无sku_name时，可传spu_name信息
        },
        spu: {
          spu_id: item.id, // 若商品无spu_id时，可传sku_id信息
          spu_name: skuLabel(item.spData), // 若商品无spu_name时，可传sku_name信息
        },
      });
  }
};

const toGoodsDetail = async (item) => {
  getApp().emdlz2(
    "track",
    "event",
    "points_store_page",
    "click",
    `product_${item.id}`,
    ""
  );
  getApp().emdlz2(
    "track",
    "event",
    "points_store_page",
    "click",
    `product_select_${item.id}`,
    ""
  );

  for (const res of item.productSkus) {
    getApp()
      .sr()
      .track("trigger_sku_component", {
        sku: {
          sku_id: res.id, // 若商品无sku_id时，可传spu_id信息
          sku_name: skuLabel(res.spData), // 若商品无sku_name时，可传spu_name信息
        },
        spu: {
          spu_id: res.id, // 若商品无spu_id时，可传sku_id信息
          spu_name: skuLabel(res.spData), // 若商品无spu_name时，可传sku_name信息
        },
      });
  }

  uni.navigateTo({ url: `/pages/goods/goods?id=${item.id}` });
};

const skuLabel = (skuData) => {
  return skuData.map(({ value, key }) => `${key}${value}`).join(" ");
};

// 打开sku选择
const openSkuChoose = (product) => {
  console.log(1111);
  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    uni.setStorageSync("REDIRECT_URI", JSON.stringify());
    uni.navigateTo({ url: "/pages/vip/register" });
    return;
  }
  if (
    getApp().globalData.user.nickname === null ||
    getApp().globalData.user.nickname === "" ||
    getApp().globalData.user.nickname === undefined
  ) {
    console.log(1);
    // cachePath.value = { path, redirect };
    return getApp().getWechatUserProfile({ navigateBack: true });
  }

  console.log(product);

  currentProduct.value = product;
  visible.value = true;
};

// 添加到购物车
const onAdd2Cart = async (data) => {
  const res = await AddProduct2Cart(data);
  if (res?.code === 200) {
    visible.value = false;
    getApp()
      .getCartCount()
      .then((res) => {
        cartCount.value = res;
      });
    getApp().emdlz2(
      "track",
      "event",
      "store_page",
      "click",
      `add_to_cart_${data.id}`,
      ""
    );

    getApp()
      .sr()
      .track("add_to_cart", {
        action_type: "append_to_cart",
        sku: {
          sku_id: data.productSkuId,
          sku_name: sku.value,
        },
        spu: {
          spu_id: data.productSkuId, // 若商品无spu_id时，可传sku_id信息
          spu_name: sku.value, // 若商品无spu_name时，可传sku_name信息
        },
        sku_num: data.quantity,
        // more...
      });

    message("加入购物车成功～");
  } else {
    message("加入购物车失败：" + res.message);
  }
};

const handleSku = (skuItem) => {
  sku.value = skuItem.key + "*" + skuItem.value;
};

const tabChoose = (item, index) => {
  isActive.value = index;
  classification.value = item;
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "click",
    `product_series_${item.name}`,
    ""
  );
};

const swiperChange = (e) => {
  isActive.value = e.detail.current;
  const item = categories.value[e.detail.current];
  classification.value = item;
  console.log(e.detail.current, classification.value);
};

const scrollChange = (e) => {
  console.log(e.detail.scrollTop);
  if (e.detail.scrollTop < 10) {
    isScrollUp.value = true;
  } else {
    isScrollUp.value = false;
  }
};

const onSearch = (keyword) =>
  uni.navigateTo({
    url: `/pages/mall/search?keyword=${keyword}`,
  });
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

:deep(.van-popup--bottom.van-popup--safe) {
  padding-bottom: 0;
}

.mall-content {
  flex: 1;
  overflow: hidden;
}
.swiper-content {
  width: 100%;
  box-sizing: border-box;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .upScroll {
    text-align: center;
    font-size: 14px;
    color: #909090;
    image {
      width: 12px;
      height: 16px;
      vertical-align: sub;
    }
  }
}
.categories-content {
  flex: 1;
  padding: 0 20px 10px 10px;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;

  .child-category {
    margin-top: 20px;
    font-size: 14px;
    text-align: center;
  }

  .goods-list {
    flex: 1;
    overflow: auto;
    .goods {
      display: flex;
      align-items: center;
      height: 88px;

      .cover {
        width: 88px;
        height: inherit;
        margin-right: 10px;
      }

      & > view {
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }

      .goods-title {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        color: #222222;
        font-size: 14px;
      }

      .goods-price {
        display: flex;
        align-items: flex-end;
        justify-content: space-between;

        .price {
          color: @primary-color;
          font-size: 16px;
          font-weight: bold;
          position: relative;
          letter-spacing: 1px;

          &::before {
            content: "¥";
            font-size: 12px;
          }
        }

        .cart {
          width: 40px;
          height: 40px;
          background: #e4ecf9;
          border-radius: 40px 0 0 0;
          position: relative;
          z-index: 10;
          image {
            width: 14px;
            height: 14px;
            position: absolute;
            top: 17px;
            right: 10px;
          }
        }
      }
    }
  }

  .categories-label {
    font-size: 14px;
    color: #505050;
    padding-bottom: 14px;
  }

  .categories-cover {
    width: 100%;
    height: 86px;
    background-color: #eeeeee;
  }
}

.mall {
  width: 100%;
  background: white;
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.mall-categories {
  width: 230rpx;
  background: white;
  overflow-y: auto;
  box-sizing: border-box;
  border-right: solid 1px #eff0f0;
  padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}

.leading-label {
  max-width: 95px;
  min-width: 95px;
  background: white;
  color: #8c8c8c;
  font-size: 14px;
  position: relative;
  box-sizing: border-box;
  border: none;
  padding: 32rpx 40rpx;
  line-height: 1.4;

  &:hover {
    background-color: transparent;
  }

  &.selected {
    color: #0058c6;

    &::before {
      content: "";
      position: absolute;
      width: 6rpx;
      height: 26rpx;
      border-radius: 0 6rpx 6rpx 0;
      background-color: @primary-color;
      top: 50%;
      left: 20rpx;
      transform: translate(0, -50%);
    }
  }
}

:deep(.van-popup) {
  z-index: 1002 !important;
}
</style>
